#include "widget.h"
#include "./ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 1. 设置窗口标题
    this->setWindowTitle("服务器");
    // 2. 实例化 TCP server
    tcpServer = new QTcpServer(this);

    // 3. 通过信号槽, 处理客户端建立的新连接.
    connect(tcpServer, &QTcpServer::newConnection, this,
            &Widget::processConnection);

    // 4. 监听端口
    bool ret = tcpServer->listen(QHostAddress::Any, 9090);
    if (!ret) {
        QMessageBox::critical(nullptr, "服务器启动失败!", tcpServer->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    // 1. 获取客户端连接
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    if (!clientSocket) {
        qWarning() << "Invalid client socket";
        return;
    }

    // 记录客户端上线
    QString log = QString("[%1:%2] 客户端上线!")
                      .arg(clientSocket->peerAddress().toString())
                      .arg(clientSocket->peerPort());
    ui->listWidget->addItem(log);

    // 2. 处理数据接收
    connect(clientSocket, &QTcpSocket::readyRead, this, [=]() {
        if (!clientSocket->bytesAvailable()) return;

        // a) 读取请求
        QString request = QString::fromUtf8(clientSocket->readAll());
        if (request.isEmpty()) return;

        // b) 处理请求并生成响应
        QString response = process(request); // 注意：不要返回const引用

        // c) 发送响应
        qint64 bytesWritten = clientSocket->write(response.toUtf8());
        if (bytesWritten == -1) {
            qDebug() << "写入失败:" << clientSocket->errorString();
        }

        // 记录通信日志
        QString log = QString("[%1:%2] req: %3, resp: %4")
                          .arg(clientSocket->peerAddress().toString())
                          .arg(clientSocket->peerPort())
                          .arg(request)
                          .arg(response);
        ui->listWidget->addItem(log);
    });

    // 3. 处理断开连接
    connect(clientSocket, &QTcpSocket::disconnected, this, [=]() {
        QString log = QString("[%1:%2] 客户端下线!")
                          .arg(clientSocket->peerAddress().toString())
                          .arg(clientSocket->peerPort());
        ui->listWidget->addItem(log);

        // 安全删除socket对象
        clientSocket->deleteLater();

        // 从客户端列表移除（如果有维护列表）
        clientSockets.removeAll(clientSocket);
    });

    // 将新连接加入客户端列表（如有需要）
    clientSockets.append(clientSocket);
}

QString Widget::process(const QString &request)
{
    return request;
}
